﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using HouseAgencySite.Models;
using HouseAgencySite.Utils;
using Newtonsoft.Json;
using Webdiyer.WebControls.Mvc;
namespace HouseAgencySite.Controllers
{
    public class HomeController : Controller
    {
        AgencyDBContext db = new AgencyDBContext();
        public ActionResult Index()
        {
            List<HtmlContents> htmlContents = db.HtmlContents
                .Where(o => o.ModuleType == 4 && o.IsDelete == false).ToList();
            foreach (var item in htmlContents)
            {
                item.AttachUrl = db.Files.OrderByDescending(o => o.ModifyTime).FirstOrDefault(o => o.ResourceID == item.Guid).Url;
            }
            HomeModel model = new HomeModel();
            model.Banners = htmlContents;
            model.HouseInfos = new List<HouseInfos>();
            for (var i = 1; i < 5; i++)
            {
                var list = db.HouseInfos.Where(o => o.IsDelete == false && o.HouseType == i).Take(3);//每种类型默认取6个放到首页展示
                if (list.Count() > 0)
                {
                    model.HouseInfos.AddRange(list);
                }
            }
            //获取图片
            foreach (var item in model.HouseInfos)
            {
                var file = db.Files.OrderByDescending(o => o.ModifyTime).OrderByDescending(o => o.ModifyTime).FirstOrDefault(o => o.ResourceID == item.Guid);//取最后上传的图片作为封面
                if (file != null)
                    item.AttachUrl = file.Url;
            }
            //企业文化
            HtmlContents company = db.HtmlContents.Where(o => o.ModuleType == 5).OrderByDescending(o => o.ModifyTime).FirstOrDefault();
            if (company != null)
            {
                ViewBag.CompanyInfo = company.ZhaiYao;
            }
            else
            {
                ViewBag.CompanyInfo = "暂无信息！";
            }
            //员工照片
            var users= db.Users.Where(o => o.IsDelete == false);
            foreach(var user in users){
           var file=db.Files.Where(o=>o.ResourceID==user.Guid).OrderByDescending(o=>o.ModifyTime).FirstOrDefault();
                if(file!=null){
                    model.Photos.Add(file.Url);
                }
            }           
            return View(model);
        }




        public ActionResult Detail(string id)
        {
            HouseInfos model = db.HouseInfos.Find(id);
            Users user = db.Users.FirstOrDefault(o => o.Guid == model.CreateUserID);
            if (user != null)
            {
                ViewBag.UserTel = user.Telephone;
                ViewBag.UserName = user.UserName;
            }
            else
            {
                ViewBag.UserTel = "暂无电话";
                ViewBag.UserName = "姓名";
            }
            return View(model);
        }

        public ActionResult Content(int id)
        {
            string title = string.Empty;
            switch (id)
            {
                case 1: title = "关于我们"; break;
                case 2: title = "贷款担保"; break;
                case 3: title = "招贤纳士"; break;
                case 5: title = "企业文化"; break;
            }
            ViewBag.Title = title;
            HtmlContents model = db.HtmlContents.Where(o => o.ModuleType == id).OrderByDescending(o => o.ModifyTime).FirstOrDefault();
            return View(model);

        }
        /// <summary>
        /// 房源信息列表
        /// </summary>
        /// <param name="id"></param>
        /// <param name="pageindex"></param>
        /// <returns></returns>
        public ActionResult HouseInfo(int id, int pageindex = 1)
        {
            string title = string.Empty;
            switch (id)
            {
                case 1: title = "出租"; break;
                case 2: title = "出售"; break;
                case 3: title = "写字楼"; break;
                case 4: title = "底商"; break;
            }
            ViewBag.Title = title;
            IPagedList pageList = db.HouseInfos.Where(o => o.IsDelete == false && o.HouseType == id).OrderByDescending(o => o.ModifyTime).ToPagedList(pageindex, 10);
            //获取图片
            foreach (var item in pageList.OfType<HouseInfos>())
            {
                var file = db.Files.OrderByDescending(o => o.ModifyTime).OrderByDescending(o => o.ModifyTime).FirstOrDefault(o => o.ResourceID == item.Guid);//取最后上传的图片作为封面
                if (file != null)
                    item.AttachUrl = file.Url;
            }
            ViewBag.T = id;
            if (Request.IsAjaxRequest())
            {
                return PartialView("SearchResult", pageList);
            }
            return View(pageList);
        }
        [ValidateInput(true)]
        public ActionResult SearchResult(int pageIndex, int orders, string model)
        {
            HouseSearchFilter filter = JsonConvert.DeserializeObject<HouseSearchFilter>(model.ToString());
            var list = db.HouseInfos.Where(o => o.IsDelete == false) as IQueryable<HouseInfos>;
            var ids = db.Areas.Where(o => o.FullPath.Contains(filter.FullPath)).Select(o => o.Guid).ToList();//地区ID
            if (ids.Count > 0)
            {
                list = list.Where(o => ids.Contains(o.AreaID));
            }
            if (filter.HouseType != 0)
            {
                list = list.Where(o => o.HouseType == filter.HouseType);
            }
            if (!string.IsNullOrEmpty(filter.Title))
            {
                list = list.Where(o => o.Title.Contains(filter.Title));
            }
            if (filter.HuXing != 0)
            {
                list = list.Where(o => o.HuXing == filter.HuXing);
            }
            if (filter.PriceLeft > 0)
            {
                list = list.Where(o => o.Price >= filter.PriceLeft);
            }
            if (filter.MianJiLeft > 0)
            {
                list = list.Where(o => o.MianJi >= filter.MianJiLeft);
            }
            if (filter.PriceRight > 0)
            {
                list = list.Where(o => o.Price <= filter.PriceRight);
            }
            if (filter.MianJiRight > 0)
            {
                list = list.Where(o => o.MianJi <= filter.MianJiRight);
            }
            if (orders == 1)
            {
                list = list.OrderByDescending(o => o.CreateTime);
            }
            else if (orders == -1)
            {
                list = list.OrderBy(o => o.CreateTime);
            }
            else if (orders == 2)
            {
                list = list.OrderByDescending(o => o.Price);
            }
            else if (orders == -2)
            {
                list = list.OrderBy(o => o.Price);
            }
            else if (orders == 3)
            {
                list = list.OrderByDescending(o => o.MianJi);
            }
            else if (orders == -3)
            {
                list = list.OrderBy(o => o.MianJi);
            }
            IPagedList<HouseInfos> pageList = list.ToPagedList(pageIndex, 10);
            //获取图片
            foreach (var item in pageList)
            {
                var file = db.Files.OrderByDescending(o => o.ModifyTime).OrderByDescending(o => o.ModifyTime).FirstOrDefault(o => o.ResourceID == item.Guid);//取最后上传的图片作为封面
                if (file != null)
                    item.AttachUrl = file.Url;
            }
            return PartialView(pageList);
        }
        /// <summary>
        /// 整站搜索
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="keywords"></param>
        /// <param name="id"></param>
        /// <returns></returns>
        [ValidateInput(true)]
        public ActionResult Search(int pageIndex = 1, string keywords = "", int id = 0)
        {
            var houseInfos = db.HouseInfos.AsQueryable<HouseInfos>();
            if (id != 0)
            {
                houseInfos = houseInfos.Where(o => o.HouseType == id);
            }
            if (!string.IsNullOrEmpty(keywords))
            {
                houseInfos = houseInfos.Where(o => o.IsDelete == false && (o.Title.Contains(keywords) || o.SubTitle.Contains(keywords) || o.ZhaiYao.Contains(keywords)));
            }
            houseInfos = houseInfos.OrderByDescending(o => o.CreateTime);
            IPagedList<HouseInfos> pageList = houseInfos.ToPagedList(pageIndex, 10);
            //获取图片
            foreach (var item in pageList)
            {
                item.Files = new List<Files>();
                var file = db.Files.OrderByDescending(o => o.ModifyTime).OrderByDescending(o => o.CreateTime).Where(o => o.ResourceID == item.Guid).ToList();//取最后上传的图片作为封面
                if (file != null)
                    item.Files = file;
            }
            return View(pageList);
        }

        #region 百度地图功能模块

        /// <summary>
        /// 百度地图
        /// </summary>
        [ActionName("baidu-map")]
        public ActionResult GetBaiduMap()
        {
            return View("~/Views/Home/BaiDuMap.cshtml");
        }

        /// <summary>
        /// 根据条件显示对应类型地图
        /// </summary>
        /// <param name="filter">地图类型条件（卫星地图，街景地图等）</param>
        [ActionName("baidu-map-partial")]
        public ActionResult BaiDuMapParPartial(string filter)
        {
            ViewData["filter"] = filter;

            return View("~/Views/Home/BaiDuMapParPartial.cshtml");
        }

        #endregion

        public ActionResult Error()
        {
            return View();
        }
    }
}
